import { ScrollView, View, Text, Image } from '@tarojs/components';
import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import Top from './components/top';
import AdvModal from '@/pages/common/adv-modal/adv-modal';
import { fetchModal, handleUrl, setModalShow, pvUvStatics } from 'wmkit';
import MemberCard from './components/memberCard';
// import CommunityModule from './components/communityModule';
// import HotShopModule from './components/hotShopModule';
import ToolsBox from './components/toolsBox';
// import GovernmentModule from './components/governmentModule';
// import BankingModule from './components/bankingModule';
import moment from 'dayjs';
// import { AtCurtain } from 'taro-ui';
// import 'taro-ui/dist/style/components/curtain.scss';
// import modelIcon from './img/model.png';
import api from 'api';
import JoinMemberModel from './components/joinMemberModel';
import RenewalMemberModel from './components/renewalMemberModel';
import NewUserModel from './components/newUserModel';
import CheckTab from './components/checkTab';
import FooterContent from './components/footerContent';
import BlacklistModel from '@/pages/common/blacklist-model';
import DoubleMenbership from './components/doubleMenbership';
import { conforms } from 'lodash';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      isModalFlag: false,
      imgUrl: '',
      jumpPage: {},
      showModel: false, //是否显示积分
      navBarHeight: 0,
      windowHeight: 0,
      joinVIP: false, //非会员(加入会员)
      renewVIP: false, //会员到期
      newVIP: false, //新会员
      refresherTriggered: false,
    };
  }

  async componentWillMount() {
    if (__TARO_ENV !== 'h5') {
      Taro.showShareMenu({
        withShareTicket: true,
      });
    }
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (itemStr) {
      this.updateModalStatus('');
    }
  }

  componentDidUpdate(prevProps: Readonly<Partial<T.IProps>>, prevState: Readonly<any>, snapshot?: any): void {

  }

  componentDidMount() {
    this.getNavHeight();
    Taro.getLocation({
      //可通过该方法获取当前位置的经纬度
      type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
      success: function (res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        Taro.setStorageSync('latitude', latitude);
        Taro.setStorageSync('longitude', longitude);
      },
    });
    // 微信不允许一直跳转登录页这段代码的生命周期不要动
    // let itemStr = Taro.getStorageSync('b2b-wechat@login');
    // if (!itemStr) {
    //   Taro.navigateTo({
    //     url: '/pages/package-C/login/login/index',
    //   });
    // }
  }

  componentDidShow() {
    // this.props.actions.clean();
    let showModel = Taro.getStorageSync('showModel');
    if (showModel) {
      this.setState({ showModel: false });
    } else {
      this.setState({ showModel: true });
    }

    const title = Taro.getStorageSync('taskModel');
    if (title) {
      Taro.showToast({
        title,
        icon: 'none',
      });
      Taro.removeStorageSync('taskModel');
    }

    
    let memberReceived = Taro.getStorageSync('memberReceived');
    if (memberReceived) {
      this.props.actions.action.getMemberBase()
    }

    this.props.actions.init();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async onShareAppMessage() {
    //触发分享，任务完成
    let task = Taro.getStorageSync('task');
    if (task) {
      task = JSON.parse(task);
      let id = task.id;
      const result = await api.TaskCenterController.completedTask({ id });
      // setTimeout(()=>{
      Taro.showToast({
        title: `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ''}${['积分', '优惠券', '实物商品'][task.taskInfoVO.rewardType]
          }${task.taskInfoVO.rewardType == 2 ? '请到我的-我的奖励中填写收货地址' : ''}`,
        icon: 'none',
      });
      Taro.removeStorageSync('task');
      Taro.setStorageSync(
        'taskModel',
        `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ''}${['积分', '优惠券', '实物商品'][task.taskInfoVO.rewardType]
        }${task.taskInfoVO.rewardType == 2 ? '请到我的-我的奖励中填写收货地址' : ''}`,
      );
      // },5000)
    }
    let wechatShareInfo = JSON.parse(Taro.getStorageSync('wechatShareInfo'));
    return {
      title: wechatShareInfo.title,
      imageUrl: wechatShareInfo.imgUrl[0].url,
    };
  }

  async updateModalStatus(id) {
    const res = await fetchModal('shoppingIndex');
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, 'shoppingIndex', popupId);
    this.setState(
      {
        isModalFlag: flagParams.showFlag,
        imgUrl: flagParams.imgUrl,
        jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
        nextPopupId: flagParams.nextPopupId,
      },
      () => {
        if (this.state.nextPopupId && !this.state.isModalFlag) {
          this.isGo(this.state.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.updateModalStatus(id);
  }
  handleClose() {
    this.setState({ isModalFlag: false }, async () => {
      if (this.state.nextPopupId) {
        await this.updateModalStatus(this.state.nextPopupId);
      }
    });
  }

  getNavHeight() {
    let menuButtonObject = Taro.getMenuButtonBoundingClientRect();
    var sysinfo = Taro.getSystemInfoSync();
    let windowHeight = sysinfo.windowHeight;
    let statusBarHeight = sysinfo.statusBarHeight;
    let menuBottonHeight = menuButtonObject.height;
    let menuBottonTop = menuButtonObject.top;
    let navBarHeight = statusBarHeight + menuBottonHeight + (menuBottonTop - statusBarHeight) * 2;
    this.setState({
      navBarHeight,
      windowHeight,
    });
  }

  _onScrollToLower = () => {
    console.log('_onScrollToLower');
    let {
      main: { pageNum, totalPages },
      actions: { action },
    } = this.props;
    let num = pageNum + 1;
    if (pageNum == totalPages) return;
    this.props.actions.action.commonChange('main.pageNum', num);
    this.props.actions.action.findMarketingcontentPage();
  };

  _onRefresherRefresh = () => {
    let { refresherTriggered } = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.props.actions.action.commonChange('main.pageNum', 0);
    this.props.actions.action.findMarketingcontentPage();
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  render() {
    let {
      main: { blacklistModel, memberCardType },
      actions: { action },
    } = this.props;
    let { windowHeight, navBarHeight, showModel, joinVIP, renewVIP, newVIP, refresherTriggered } = this.state;
    return (
      <View className="packageRzIndex">
        <Top />
        <ScrollView
          style={{ height: windowHeight - navBarHeight - 66 }}
          onScrollToLower={this._onScrollToLower}
          refresherEnabled
          refresherBackground={memberCardType == "noMember" || memberCardType == "lanjing" ? '#5A95FF' : memberCardType == "chijing" ? '#F6C1BA' : memberCardType == "shuangchong" ? '#D29E68' : '#5A95FF'}
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}
          scrollY
        >
          <View className="topBgBox">
            <View className={`topBgBox-bg topBgBox-bg-${memberCardType}`}></View>
            <ToolsBox />
          </View>
          <View className="homeContent">
            <MemberCard />
            <View>
              <CheckTab></CheckTab>
              <FooterContent />
            </View>
          </View>
        </ScrollView>
        {/* <JoinMemberModel />
        <RenewalMemberModel /> */}
        {/* 限时双会员 */}
        <DoubleMenbership />
        <NewUserModel />
        <BlacklistModel
          isOpened={blacklistModel}
          onConfirm={() => {
            action.commonChange('main.blacklistModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.blacklistModel', false);
          }}
        />
        <AdvModal
          imgUrl={this.state.imgUrl}
          handleUrl={() => handleUrl(this.state.jumpPage)}
          handleClose={() => this.handleClose()}
          isModalFlag={this.state.isModalFlag}
        />
      </View>
    );
  }
}
